import Cookies from "js-cookie";

const TOKEN_KEY = "satoken";

const isLogin = () => {
  return !!Cookies.get(TOKEN_KEY);
};

const getToken = () => {
  return Cookies.get(TOKEN_KEY);
};
const setToken = (token: string) => {
  Cookies.set(TOKEN_KEY, token);
};
const removeToken = () => {
  Cookies.remove(TOKEN_KEY);
};

// 设置用户信息
const setUserCookie = (userCookie: UserCookie) => {
  return Cookies.set("userCookie", JSON.stringify(userCookie));
};

// 获取用户信息
const getUserCookie = (): UserCookie => {
  return JSON.parse(Cookies.get("userCookie") || "{}") as UserCookie;
};

// 清除用户信息
const clearUserCookie = () => {
  Cookies.remove("userCookie");
};

// 清除token和用户信息
const clearTokenAndUserCookie = () => {
  removeToken();
  clearUserCookie();
};

// 定义用户类型
class UserCookie {
  userId: number;
  username: string;
  avatar: string;
  role: string;

  constructor(userId: number, username: string, avatar: string, role: string) {
    this.userId = userId;
    this.username = username;
    this.avatar = avatar;
    this.role = role;
  }
}

export {
  isLogin,
  getToken,
  setToken,
  removeToken,
  setUserCookie,
  getUserCookie,
  clearUserCookie,
  clearTokenAndUserCookie,
  UserCookie,
};
